Renaming levels of a factor
Problem
You want to do rename the levels in a factor.
Solution
# A sample factor to work with. x <- factor(c("alpha","beta","gamma","alpha","beta")) # alpha beta gamma alpha beta # Levels: alpha beta gamma levels(x) # "alpha" "beta" "gamma" # Rename by name: change "beta" to "two" levels(x)[levels(x)=="beta"] <- "two" # "alpha" "two" "gamma" # Rename by index in levels list: change third item, "gamma", to "three" levels(x)[3] <- "three" # "alpha" "two" "three" # Rename all levels levels(x) <- c("one","two","three") # "one" "two" "three"
It's also possible to use R's string search-and-replace functions to rename factor levels. Note that the ^
and $
surrounding alpha
are there to ensure that the entire string matches. Without them, if there were a level named alphabet
, it would also match, and the replacement would be onebet
.
# A sample factor to work with. x <- factor(c("alpha","beta","gamma","alpha","beta")) # alpha beta gamma alpha beta # Levels: alpha beta gamma levels(x) <- sub("^alpha$", "one", levels(x)) # one beta gamma one beta # Levels: one beta gamma # Across all columns, replace all instances of "a" with "X" levels(x) <- gsub("a", "X", levels(x)) # one betX gXmmX one betX # Levels: one betX gXmmX # gsub() replaces all instances of the pattern in each factor level. # sub() replaces only the first instance in each factor level.